#include "App.h"
#include "DebugTracer.h"

extern DebugTracer _DEBUGTRACER;
App::App():m_root(0)
{
    m_game = NULL;
    m_gameView = NULL;
    m_root = NULL;
    m_window = NULL;
    m_sceneManager = NULL;
    m_camera = NULL;
}

App::~App()
{
    delete m_root;
}
bool App::Start()
{
    #ifdef _DEBUG
    m_root = new Ogre::Root("conf/plugins_d.cfg","log/ogre.cfg","log/ogre.log");
    #else
    m_root = new Ogre::Root("conf/plugins.cfg","log/ogre.cfg","log/ogre.log");
    #endif
    Ogre::ConfigFile configFile;
    configFile.load("conf/resources.cfg");
    Ogre::ConfigFile::SectionIterator seci = configFile.getSectionIterator();
    Ogre::String secName, typeName, archName;
    while(seci.hasMoreElements())
    {
        secName = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for(i = settings->begin(); i != settings->end(); ++i)
        {
            typeName = i->first;
            archName = i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName,typeName,secName);
        }
    }
    Ogre::RenderSystem *rs = m_root->getRenderSystemByName("Direct3D9 Rendering Subsystem"); // Pour OpenGL : "OpenGL Rendering Subsystem"
    m_root->setRenderSystem(rs);
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("Video Mode", "1024 x 768 @ 32-bit colour");
    rs->setConfigOption("VSync", "Yes");

    m_window = m_root->initialise(true, "openfzero");
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
    Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    m_sceneManager = m_root->createSceneManager("DefaultSceneManager","My scene manager");

    //TEST
    m_sceneManager->setAmbientLight(Ogre::ColourValue(1.0f,1.0f,1.0f));

    m_game = new Game(m_sceneManager->getRootSceneNode());

    m_gameView = new GameView(m_window,m_sceneManager,m_game);



    while(true)
    {
        Ogre::WindowEventUtilities::messagePump();

        if(m_window->isActive())
        {
            m_gameView->Update(1/m_window->getLastFPS());
            m_game->Update(1/m_window->getLastFPS());

             if(!m_root->renderOneFrame())
                    return false;
        }
        else
        {
            m_root->clearEventTimes();
        }

        if(m_window->isClosed())
            return false;
    }
    return true;
}
